package auth

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"go.uber.org/zap"
	"navi-mumbai/app/api/admin/internal/model/pg"
	"strconv"
	"time"
)

var logger logx.Logger = logx.WithDuration(time.Second)

func WriteAdminLog(ctx context.Context, logModel pg.ApiLogModel, adminUid int64, api int64, req interface{}, resp interface{}, errIn error) {
	var reqStr, respStr string
	if req != nil {
		buf, err := json.Marshal(req)
		if err != nil {
			logger.Errorf("err == ", zap.Error(err))
			logx.WithContext(ctx).Errorf("WriteAdminLog Marshal req err : %+v", err)
			return
		}
		reqStr = string(buf)
	}
	if errIn != nil {
		respStr = errIn.Error()
	} else {
		if resp != nil {
			buf, err := json.Marshal(resp)
			if err != nil {
				logger.Errorf("err == ", zap.Error(err))
				logx.WithContext(ctx).Errorf("WriteAdminLog Marshal resp err : %+v", err)
				return
			}
			respStr = string(buf)
		}
	}

	adminLog := pg.ApiLog{
		Uid:      adminUid,
		Api:      strconv.FormatInt(api, 10),
		ReqParam: reqStr,
		Response: respStr,
	}
	_, err := logModel.Insert(ctx, &adminLog)
	if err != nil {
		logger.Errorf("err == ", zap.Error(err))
		logx.WithContext(ctx).Errorf("WriteAdminLog Insert err : %+v", err)
		return
	}
	return
}
